package com.example.util;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelperWithoutGreenDAO extends SQLiteOpenHelper {
	private final static int VERSION = 1;
	private final static String DB_NAME = "my.db";
	private final static String TABLE_NAME = "diary";

	private SQLiteDatabase db;
	private static DBHelperWithoutGreenDAO dh;
	
	//创建日记表
  	public String CREATE_TABLE_DIARY = "CREATE TABLE IF NOT EXISTS "
  			+ "diary"
  			+ "(id integer primary key autoincrement,"
  			+ "title varchar(40),"
  			+ "content varchar(250),"
  			+ "time DATETIME DEFAULT CURRENT_TIMESTAMP)";
  	
  	public static DBHelperWithoutGreenDAO getInstance(Context context){
  		if (dh == null) {
            dh = new DBHelperWithoutGreenDAO(context);
        }
        return dh;
  	}
  	
	public DBHelperWithoutGreenDAO(Context context, String name, CursorFactory factory,int version) {
		super(context, name, factory, version);
	}
	
	private DBHelperWithoutGreenDAO(Context context){
		this(context, DB_NAME, null, VERSION);
	}
	
    //创建一个数据库
	@Override
	public void onCreate(SQLiteDatabase db) {
		this.db = db;
		System.out.println("Create Database");
		db.execSQL(CREATE_TABLE_DIARY);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		System.out.println("update Database");

	}
	
	//插入方法
	public void insert(String[] paramName,String[] paramValue){
		//获取SQLiteDatabase实例
		SQLiteDatabase db = getWritableDatabase();
		int len = paramName.length;
		ContentValues values = new ContentValues();  
		for(int i = 0;i < len;i++){
	        values.put(paramName[i], paramValue[i]);
		}
		//插入数据库中
		db.insert(TABLE_NAME, null, values);
		db.close();
	}
	
	//查询方法
	public Cursor query(){
		SQLiteDatabase db = getReadableDatabase();

		//获取Cursor
		Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null, null);

		return c;
		
	}
	
	//根据唯一标识_id  来删除数据
	public void delete(int id){
		SQLiteDatabase db = getWritableDatabase();
		db.delete(TABLE_NAME, "_id=?", new String[]{String.valueOf(id)});
	}
	
	
	//更新数据库的内容
	public void update(ContentValues values, String whereClause, String[]whereArgs){
		SQLiteDatabase db = getWritableDatabase();
		db.update(TABLE_NAME, values, whereClause, whereArgs);
	}
	
	//关闭数据库
	public void close(){
		if(db != null){
			db.close();
		}
	}

}